/** @format */

import { connect, Connection, Channel, ConsumeMessage } from 'amqplib';
import { basename } from 'path';

const AMQP_SERVIC = 'amqp://gj:123qwe@10.0.0.215:5672';
const RECORD_MQ_EXCHANGE = 'recordMQ';
const RECORD_MQ_EXCHANGE_TYPE = 'topic';
// const RECORD_MQ_QUEUE = `record[${Date.now()}]`;
const RECORD_MQ_QUEUE = `record`;

let amqp: Connection | undefined = undefined;
let channel: Channel | undefined = undefined;

// console.log(process.argv);
// const keys = process.argv.slice(2);
// if (keys.length < 1) {
//     console.log('Usage: %s pattern [pattern...]', basename(process.argv[1]));
//     process.exit(1);
// }

const keys = ['#.record', '#.add'];

async function init(): Promise<void> {
    amqp = await connect(AMQP_SERVIC);
    channel = await amqp.createChannel();
}

async function bootstrap(): Promise<void> {
    await init();
    if (channel) {
        await channel.assertExchange(RECORD_MQ_EXCHANGE, RECORD_MQ_EXCHANGE_TYPE, {
            // durable?: boolean;
            // internal?: boolean;
            // autoDelete?: boolean;
            // alternateExchange?: string;
            // arguments?: any;
            durable: true, // 持久
            autoDelete: false, //自动删除
        });
        await channel.assertQueue(RECORD_MQ_QUEUE, {
            // exclusive?: boolean;
            // durable?: boolean;
            // autoDelete?: boolean;
            // arguments?: any;
            // messageTtl?: number;
            // expires?: number;
            // deadLetterExchange?: string;
            // deadLetterRoutingKey?: string;
            // maxLength?: number;
            // maxPriority?: number;
            exclusive: false, //独占
            autoDelete: false, //自动删除
        });
        for (let index = 0; index < keys.length; index++) {
            const key = keys[index];
            console.log(`bind key: ${key}`);
            await channel.bindQueue(RECORD_MQ_QUEUE, RECORD_MQ_EXCHANGE, key);
        }
        await channel.consume(
            RECORD_MQ_QUEUE,
            (msg: ConsumeMessage | null) => {
                if (msg) {
                    console.log(`${msg.content.toString()} => [${Date.now()}]`);
                }
            },
            {
                // consumerTag?: string;
                // noLocal?: boolean;
                // noAck?: boolean;
                // exclusive?: boolean;
                // priority?: number;
                // arguments?: any;
                noAck: false, // 自动ACK
            },
        );
    }
}
bootstrap();
